<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-05-10
 * @Time: 15:23
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： DynamicComment.php
 */
namespace app\api\model\dynamic;

use app\api\model\user\Users;
use think\Db;
use think\Log;
use think\Model;

class DynamicComment extends Model {
    protected $table = 'dynamic_comment';
    protected $pk = 'id';

    /**
     * getAllComment
     * 获取全部动态评论数据
     *
     * @author zhengkai
     * @date 2018-05-10
     *
     * @param int $id 动态
     * @param int $page 当前页数
     * @param int $limit 每页查询数据条数
     * @return array
     */
    public static function getAllComment($id, $page=1, $limit=10)
    {
        $data = self::all(function($query) use ($id, $page, $limit) {
            $query->alias('dc')
                ->field('dc.id as comment_id, dc.content, dc.times, u.id as user_id,u.mobile as user_mobile, u.nickname as user_nickname, u.avatar as user_avatar')
                ->join('users u', 'dc.user_id=u.id', 'left')
                ->where('dc.dynamic_id', $id)
                ->order('dc.dynamic_id desc')
                ->page($page, $limit);
        });

        if (!$data) return [];

        foreach ($data as &$val) {
            $val['user_nickname'] = ($val['user_nickname']?:mobile_hidden(substr($val['user_mobile'], 0, 11)))?:$val['user_id'];
            $val['user_avatar'] = $val['user_avatar']?:Users::defaultAvatar();

            $val['times'] = tranTime($val['times']);

            unset($val['user_id'], $val['user_mobile']);
        }

        return $data;
    }

    /**
     * createComment
     * 新增评论数据
     *
     * @author zhengkai
     * @date 2018-05-10
     *
     * @param array $param
     * @return bool
     */
    public static function createComment($param=[])
    {
        Db::startTrans();
        try {
            $res = self::create($param);
            Db::commit();

            DynamicM::updateCommentCount($res->dynamic_id);

            return true;
        } catch (\Exception $e) {
            Log::error('新增动态评论【error】：'.$e->getMessage());

            Db::rollback();

            return false;
        }
    }
}